package com.hixtrip.sample.config;

import com.hixtrip.sample.client.exception.ServiceException;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;

/**
 * 全局异常处理器
 */
@RestControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    /**
     * 业务异常
     */
    @ExceptionHandler(ServiceException.class)
    public HashMap<String, Object> handleServiceException(ServiceException e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        Integer code = e.getCode();
        if (code == null){
            return createResult(e.getMessage());
        }
        return createResult(code, e.getMessage());
    }

    /**
     * 系统异常
     */
    @ExceptionHandler(Exception.class)
    public HashMap<String, Object> handleException(Exception e, HttpServletRequest request) {
        log.error(e.getMessage(), e);
        return createResult(e.getMessage());
    }

    public static HashMap<String, Object> createResult(String msg){
        return createResult(500, msg);
    }

    public static HashMap<String, Object> createResult(Integer code , String msg){
        HashMap<String, Object> result = new HashMap<>();
        result.put("code", code);
        result.put("msg", msg);
        return result;
    }
}
